﻿using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Xenta.Utils
{
    /// <summary>
    /// Represents the URL helper.
    /// </summary>
    public static class UrlUtility
    {
        #region Methods

        /// <summary>
        /// Converts the string to the SEO optimized string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The SEO optimized string.</returns>
        public static string ToSeoFriendly(string s)
        {
            if(String.IsNullOrEmpty(s))
            {
                return String.Empty;
            }

            s = s.ToLower();
            s = Regex.Replace(s, @"[^\w\.\-\s]", String.Empty);
            s = s.Replace(' ', '-');
            s = Regex.Replace(s, @"-{2,}", "-");
            s = s.TrimStart('-', '.');
            s = s.TrimEnd('-', '.');

            if(s.Length > 80)
            {
                s = s.Substring(0, 79);
            }

            s = s.TrimEnd('-');

            return s;
        }

        /// <summary>
        /// Encodes the URL string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The encoded string.</returns>
        public static string Encode(string s)
        {
            return HttpUtility.UrlEncode(s);
        }

        /// <summary>
        /// Decodes the URL string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The decoded string.</returns>
        public static string Decode(string s)
        {
            return HttpUtility.UrlDecode(s);
        }

        #endregion
    }
}
